package com.power.sifa.netlogin.service.impl;

import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.netlogin.dao.Net_userDao;
import com.power.sifa.netlogin.model.Net_user;
import com.power.sifa.netlogin.model.pageInfo.Net_userPageInfo;
import com.power.sifa.netlogin.service.Net_userService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *  申诉端登录用户实体业务层实现
 */
@Service
public class Net_userServiceImpl extends BaseServiceImpl implements Net_userService {

    @Autowired
    private Net_userDao dao;

    @Override
    public Net_user getById(String id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Net_user net_user) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (net_user.getPrimaryKey() != null) {
        	 Net_user net_userfDb = dao.findById(net_user.getPrimaryKey()).orElse(null);
             if(net_userfDb != null) {
                BeanUtils.copyProperties(net_user, net_userfDb);
                dao.save(net_userfDb);
                return;
             }
        }
        dao.save(net_user);
    }

    @Override
    public void removeById(String id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Net_user> findAll(Net_userPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Net_user> findAll() {
		return dao.findAll();
	}
	
	@Override
	public void saveAll(List<Net_user> list) {
		dao.saveAll(list);
	}

    @Override
    public Net_user getByPhone(String phone) {
        // 根据号码查询对应的用户信息
        Specification<Net_user> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("phone"), phone))
        ).getRestriction();
        return dao.findOne(specification).orElse(null);
    }
}
